﻿#define _CRT_SECURE_NO_WARNINGS

#include "smart_ptr.h"

struct Date
{
	int _year;
	int _month;
	int _day;
	Date(int year = 1, int month = 1, int day = 1)
		:_year(year)
		, _month(month)
		, _day(day)
	{
	}
	~Date()
	{
		cout << "~Date()" << endl;
	}
};

//int main()
//{
//	//ljh::auto_ptr<Date> ap1(new Date);
//	//// 拷⻉时，管理权限转移，被拷⻉对象ap1悬空
//	//ljh::auto_ptr<Date> ap2(ap1);
//	// //空指针访问，ap1对象已经悬空
//	////ap1->_year++;
//	//ljh::unique_ptr<Date> up1(new Date);
//	//// 不⽀持拷⻉
//	////unique_ptr<Date> up2(up1);
//	//// ⽀持移动，但是移动后up1也悬空，所以使⽤移动要谨慎
//	//ljh::unique_ptr<Date> up3(move(up1));
//
//	ljh::shared_ptr<Date> sp1(new Date);
//	// ⽀持拷⻉
//	ljh::shared_ptr<Date> sp2(sp1);
//	ljh::shared_ptr<Date> sp3(sp2);
//	cout << sp1.use_count() << endl;
//	sp1->_year++;
//	cout << sp1->_year << endl;
//	cout << sp2->_year << endl;
//	cout << sp3->_year << endl;
//	return 0;
//}

int main()
{
	std::shared_ptr<string> sp1(new string("111111"));
	std::shared_ptr<string> sp2(sp1);
	std::weak_ptr<string> wp = sp1;
	cout << wp.expired() << endl;//0
	cout << wp.use_count() << endl;//2

	// sp1和sp2都指向了其他资源，则weak_ptr就过期了
	sp1 = make_shared<string>("222222");
	cout << wp.expired() << endl;//0
	cout << wp.use_count() << endl;//1

	sp2 = make_shared<string>("333333");
	cout << wp.expired() << endl;//1 -说明资源过期了
	cout << wp.use_count() << endl;//0 -说明没有指针指向111111了

	wp = sp1;
	//std::shared_ptr<string> sp3 = wp.lock();
	auto sp3 = wp.lock();//返回sp1，即222222，让sp3也指向他
	cout << wp.expired() << endl;//0
	cout << wp.use_count() << endl;//2
	*sp3 += "###";//222222###

	cout << *sp1 << endl;
	return 0;
}